package com.zkingsoft.actions.admin;

import java.io.File;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.collections.CollectionUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.zkingsoft.actions.common.BaseController;
import com.zkingsoft.anotations.RemoveRequestToken;
import com.zkingsoft.anotations.SaveRequestToken;
import com.zkingsoft.dao.InterfaceCateDao;
import com.zkingsoft.model.CaseStep;
import com.zkingsoft.model.CommonUserCase;
import com.zkingsoft.model.InterfaceCate;
import com.zkingsoft.model.Project;
import com.zkingsoft.model.UserCase;
import com.zkingsoft.plugin.pojo.PaginationVO;
import com.zkingsoft.plugin.util.ExcelImport;
import com.zkingsoft.plugin.util.ExcelUtil;
import com.zkingsoft.plugin.util.ExcelUtil.ViewExcel;
import com.zkingsoft.plugin.util.WebUtil;
import com.zkingsoft.pojo.AjaxResult;
import com.zkingsoft.services.CaseStepService;
import com.zkingsoft.services.CommonUserCaseDaoService;
import com.zkingsoft.services.ProjectService;
import com.zkingsoft.services.UserCaseService;

/**
 * @author admin
 * @date 2017-02-06 用例管理Controller
 */
@Controller
@RequestMapping(value = "admin/userCase")

public class UserCaseController extends BaseController {

	@Resource
	private UserCaseService currentService;
	@Resource
	private CaseStepService caseStepService;

	@Resource
	private ProjectService projService;

	/**
	 * 列表显示
	 */
	@RequestMapping(value = "/showList")
	public @ResponseBody AjaxResult showList(UserCase UserCase, PaginationVO pageVo) {
		return showList(currentService, UserCase, pageVo);
	}

	@RequestMapping(value = "/findStep")
	public @ResponseBody AjaxResult findStep(UserCase userCase) {
		List<UserCase> userCasesList = currentService.findByModel(userCase);
		return new AjaxResult(AjaxResult.STATUS_OK, userCasesList.get(0).getStepsNoHistory());
	}

	/**
	 * 分组获取用例的执行历史记录
	 */
	@RequestMapping(value = "/showHistoryList")
	public @ResponseBody AjaxResult showHistoryList(Long caseId) {
		List<List<CaseStep>> row = caseStepService.findHistoryList(caseId);
		return new AjaxResult(AjaxResult.STATUS_OK, null, "", row, null);
	}

	/**
	 * 新增或者修改页面
	 */
	@RequestMapping(value = "/addOrModify")
	@RemoveRequestToken
	public @ResponseBody AjaxResult addOrModify(UserCase UserCase) {
		if (UserCase.getCaseId() != null) {
			return modify(currentService, UserCase, "用例");
		} else {
			UserCase.setUserId(getMe().getId());
			UserCase.setCreateTime(new Date());
			UserCase.setCaseStatus("正常");
			UserCase.setSuccess(0);
			UserCase.setFail(0);
			UserCase.setCaseNo(currentService.findMaxNo(UserCase.getProjId()) + 1);
			return add(currentService, UserCase, "用例");
		}

	}

	/**
	 * 进入修改界面
	 */
	@RequestMapping(value = "/editForm")
	@SaveRequestToken
	public String editForm(Long id) {
		UserCase UserCase;
		if (id != null) {
			UserCase = currentService.findById(id);
			WebUtil.getRequest().setAttribute("obj", UserCase);
		}
		return "admin/UserCase-form";
	}

	/**
	 * 进入执行界面
	 */
	@RequestMapping(value = "/exeCase")
	@SaveRequestToken
	public String exeCase(Long id) {
		editForm(id);
		return "admin/exe-case";
	}

	/**
	 * 进入执行界面
	 */
	@RequestMapping(value = "/doExeCase")
	@ResponseBody
	public AjaxResult doExeCase(UserCase userCaser) {
		currentService.exeCase(userCaser, getMe());
		return new AjaxResult(AjaxResult.STATUS_OK, null, "执行完毕");
	}

	/**
	 * 删除
	 */
	@RequestMapping(value = "/del")
	public @ResponseBody AjaxResult del(String keys) {
		System.out.println(keys);
		return remove(currentService, keys);
	}

	/**
	 * 删除
	 * 
	 * @throws DocumentException
	 */
	@RequestMapping(value = "/importFile")
	public @ResponseBody AjaxResult importFile(String keys) throws DocumentException {
		File file = new File("/Users/admin/Desktop/123.xml");

		SAXReader reader = new SAXReader();
		Document doc = reader.read(file);
		Element rows = doc.getRootElement().element("rows");
		Element Record;
		for (Iterator<?> i = rows.elementIterator("row"); i.hasNext();) {
			UserCase userCase = new UserCase();
			Record = (Element) i.next();
			userCase.setProjId(22L);
			userCase.setUserId(getMe().getId());
			userCase.setCreateTime(new Date());
			userCase.setCaseStatus("正常");
			userCase.setSuccess(0);
			userCase.setFail(0);
			userCase.setCaseNo(currentService.findMaxNo(userCase.getProjId()) + 1);
			userCase.setTitle(Record.elementText("title"));
			userCase.setBeforCondition(Record.elementText("precondition"));
			userCase.setGrade(Integer.parseInt(Record.elementText("pri")));
			userCase.setCaseType("功能测试");
			userCase.setUserStage("单元测试阶段");
			// 设置步骤
			String[] stepDesc = Record.elementText("stepDesc").split("<br />");
			String[] stepExpect = Record.elementText("stepExpect").split("<br />");
			List<CaseStep> stepList = new ArrayList<>();
			for (int i1 = 0; i1 < stepDesc.length; i1++) {
				CaseStep step = new CaseStep();
				String stepNo = stepExpect[i1].substring(0, stepExpect[i1].indexOf("."));
				String title = stepDesc[i1].substring(stepDesc[i1].indexOf(".") + 1);
				String expectation = stepExpect[i1].substring(stepExpect[i1].indexOf(".") + 1);
				step.setStepNo(Integer.parseInt(stepNo));
				step.setTitle(title);
				step.setExpectation(expectation);
				stepList.add(step);
			}
			userCase.setStepsNoHistory(stepList);
			currentService.add(userCase);
		}
		return remove(currentService, keys);
	}

	@Resource
	private CommonUserCaseDaoService commonUserCaseDaoService;

	/**
	 * 2018/07/27 GAOKE 进入通用用例导入界面
	 */
	@RequestMapping(value = "/putInForm")
	@SaveRequestToken
	public String putInForm(Long id) {
		CommonUserCase commonUserCase;
		if (id != null) {
			commonUserCase = commonUserCaseDaoService.findById(id);
			WebUtil.getRequest().setAttribute("obj", commonUserCase);
		}
		return "admin/UserCasePutIn-form";
	}

	/**
	 * 2018/07/30 GAOKE 导入
	 */
	@RequestMapping(value = "/putIn")
	public AjaxResult putIn(String[] caseIds, String modelId, String projId) {
		// 拿到了所有的通用用例的id 和 工程模块 id 和工程id
		// System.out.println(caseIds+"---------"+modelId+"---------"+projId);
		int maxno = currentService.findMaxNo(Long.parseLong(projId));
		for (int i = 0; i < caseIds.length; i++) {
			// 通过通用用例id查找出对应的通用用例信息
			CommonUserCase uc2 = commonUserCaseDaoService.findById(Long.parseLong(caseIds[i]));
			// 将通用用例中的信息复制到项目用例中来
			UserCase userCase = new UserCase();
			userCase.setBeforCondition(uc2.getBeforCondition());
			userCase.setCaseStatus(uc2.getCaseStatus());
			userCase.setCaseType(uc2.getCaseType());
			userCase.setFail(0);
			userCase.setSuccess(0);
			userCase.setGrade(uc2.getGrade());
			userCase.setKeyworld(uc2.getKeyworld());
			userCase.setRemark(uc2.getRemark());
			userCase.setTitle(uc2.getTitle());
			userCase.setUserStage(uc2.getUserStage());
			// 如果没有选择项目中的具体模块,则主动置空
			if (modelId == null || modelId.equals("") || modelId.equals("undefined")) {
				userCase.setModelId(null);
			} else {
				userCase.setModelId(Long.parseLong(modelId));
			}
			userCase.setProjId(Long.parseLong(projId));
			userCase.setCaseNo(++maxno);
			userCase.setUserId(getMe().getId());
			userCase.setCreateTime(new Date());
			userCase.setStepsNoHistory(uc2.getStepsNoHistory());
			currentService.putIn(userCase);
		}
		return new AjaxResult(AjaxResult.STATUS_OK, null, null);
	}

	/*
	 * showFrom 打开展示详情 的页面
	 */
	@RequestMapping(value = "/showFrom")
	@SaveRequestToken
	public String showFrom(Long id) {
		CommonUserCase commonUserCase;
		if (id != null) {
			commonUserCase = commonUserCaseDaoService.findById(id);
			WebUtil.getRequest().setAttribute("more", commonUserCase);
		}
		return "admin/commonUserCase-show";
	}

	/**
	 * excel导入
	 * 
	 * @throws Exception
	 */
	@RequestMapping(value = "/importData")
	public @ResponseBody AjaxResult importData(HttpServletResponse response, HttpServletRequest request,
			@RequestParam(value = "file", required = false) MultipartFile file) throws Exception {
		// 获取工程id
		String projID = request.getParameter("projId");
		// 获取文件名
		String fileName = file.getOriginalFilename();
		// 获取文件存放路径
		String dirPath = request.getSession().getServletContext().getRealPath("/") + "fileupload";
		File fileDir = new File(dirPath);
		// 检查目录
		if (!fileDir.exists()) {
			if (!fileDir.mkdirs()) {
				throw new Exception("创建文件失败");
			}
		}
		File saveFile = new File(dirPath + "/" + fileName);
		// 把内存文件写入磁盘中
		file.transferTo(saveFile);
		// 读取Excel中的数据
		List<List<Object>> data = ExcelImport.readExcel(saveFile, fileName, null, null);
		// 将读取的数据存入数据库
		List<UserCase> userCaseList = saveData(data, projID);
		int maxno = currentService.findMaxNo(Long.parseLong(projID));
		for (UserCase userCase : userCaseList) {
			userCase.setCaseNo(++maxno);
			userCase.setUserId(getMe().getId());
			currentService.putInByExcel(userCase);
		}

		if (CollectionUtils.isNotEmpty(userCaseList)) {
			return new AjaxResult("成功", userCaseList);
		} else {
			return new AjaxResult("失败", userCaseList);
		}
	}

	/**
	 * 用例导出 @author 姜友瑶 @date 2018年12月9日 @email 250269931@qq.com @throws
	 */
	@RequestMapping(value = "/exportUserCaseExcel")
	public @ResponseBody ModelAndView outPut(UserCase userCase, ModelMap model, HttpServletRequest request,
			HttpServletResponse response) {
		// 设置filename：导出文件名
		response.setHeader("Content-disposition", "filename=export.xlsx");

		List<UserCase> userCasesList = currentService.findByModel(userCase);

		Project project = projService.findById(userCase.getProjId());

		// 组合数据
		List<List<Object>> dataList = new ArrayList<>();
		DateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm");

		for (UserCase userCaseTemp : userCasesList) {

			for (CaseStep caseStep : userCaseTemp.getStepsNoHistory()) {
				List<Object> temp = new ArrayList<>();
				temp.add(userCaseTemp.getModelName());
				temp.add(userCaseTemp.getTitle());
				temp.add(userCaseTemp.getCaseType());
				temp.add(userCaseTemp.getBeforCondition());
				temp.add(userCaseTemp.getUserStage());
				temp.add(userCaseTemp.getUserName());
				temp.add(caseStep.getStepNo());
				temp.add(caseStep.getTitle());
				temp.add(caseStep.getExpectation());
				temp.add(caseStep.getResult());
				temp.add(caseStep.getActually());
				temp.add(caseStep.getExeUser());
				if (caseStep.getExeTime() != null) {
					temp.add(fmt.format(caseStep.getExeTime()));
				}
				dataList.add(temp);

			}

		}

		// 调用我们的excel工具类，导出数据
		HSSFWorkbook workbook = ExcelUtil.generateExcel(project.getProjName() + "用例列表", new String[] { "功能模块", "用例名称",
				"用例类型", "前置条件", "适用阶段", "创建人", "步骤序号", "步骤", "预期结果", "测试结果", "结果描述", "执行人", "执行日期" }, dataList);
		try {
			ViewExcel.buildExcel(null, workbook, request, response, project.getProjName() + "用例导出.xls");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return new ModelAndView(new ViewExcel(), model);
	}

	@Autowired
	private InterfaceCateDao interfaceCateDao;

	/**
	 * 将读取的数据存入数据库
	 * 
	 * @throws Exception
	 */
	private List<UserCase> saveData(List<List<Object>> excelData, String projId) {
		List<UserCase> data = new ArrayList<UserCase>();
		if (CollectionUtils.isNotEmpty(excelData)) {
			for (int i = 1; i < excelData.size() - 1; i++) {
				List<Object> objList = excelData.get(i);
				String mobleName;
				if (CollectionUtils.isNotEmpty(objList)) {
					UserCase userCase = new UserCase();
					// 通过工程名 与 模块名称查找到模块id
					mobleName = objList.get(0).toString();
					InterfaceCate interfaceCate = interfaceCateDao.hasInterfaceCate(Long.parseLong(projId), mobleName);
					if (interfaceCate == null) {
						userCase.setModelId(null);
						;
					} else {
						userCase.setModelId(interfaceCate.getId());
					}
					userCase.setProjId(Long.parseLong(projId));
					userCase.setTitle(objList.get(1).toString());
					userCase.setBeforCondition(objList.get(3).toString());
					userCase.setGrade((int) Math.ceil(Double.valueOf(objList.get(2).toString())));
					userCase.setSuccess((int) Math.ceil(Double.valueOf(objList.get(7).toString())));
					userCase.setFail((int) Math.ceil(Double.valueOf(objList.get(8).toString())));
					userCase.setRemark(objList.get(9).toString());
					userCase.setCaseStatus("正常");
					userCase.setCreateTime(new Date());

					// 导入简单的用例步骤
					CaseStep caseStep = new CaseStep();
					List<CaseStep> stepsNoHistory = new ArrayList<>();
					caseStep.setTitle(objList.get(4).toString());
					caseStep.setExpectation(objList.get(5).toString());
					caseStep.setActually(objList.get(6).toString());
					stepsNoHistory.add(caseStep);
					userCase.setStepsNoHistory(stepsNoHistory);
					data.add(userCase);
				}
			}
			return data;
		}
		return null;
	}

}